﻿namespace com.game.basic.events
{
    using System;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.Events;

    public class EventDispatcher : IEventDispatcher
    {
        private Dictionary<string, EventObject> eventDic = new Dictionary<string, EventObject>();

        public void AddEventListener(string type, UnityAction<EventObject> listener)
        {
            if (this.eventDic.ContainsKey(type))
            {
                if (this.eventDic[type] != null)
                {
                    this.eventDic[type].AddListener(listener);
                }
                else
                {
                    this.eventDic[type] = new EventObject(type, null);
                    this.eventDic[type].AddListener(listener);
                }
            }
            else
            {
                this.eventDic.Add(type, new EventObject(type, null));
                this.eventDic[type].AddListener(listener);
            }
        }

        public void Dispatcher(EventObject evt)
        {
            if (this.eventDic.ContainsKey(evt.EventType))
            {
                evt = this.eventDic[evt.EventType];
                this.eventDic[evt.EventType].Target = this;
                this.eventDic[evt.EventType].CurrentTarget = this;
                this.eventDic[evt.EventType].Invoke(evt);
            }
            else
            {
                Debug.LogWarning("firstly add Event listener");
            }
        }

        public bool HasEventListener(string type)
        {
            return this.eventDic.ContainsKey(type);
        }

        public void RemoveEventListener(string type, UnityAction<EventObject> listener)
        {
            if (this.eventDic.ContainsKey(type))
            {
                this.eventDic[type].RemoveListener(listener);
            }
        }
    }
}

